package com.quasar.hpatient.view.personal;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.choicePhoto.Global;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.controllermodel.PictureConstant;
import com.quasar.hpatient.model.custommodel.PhotoModel;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.DataHeadResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.Aerainfodb;
import com.quasar.hpatient.model.litePalmodel.BloodTypeInfodb;
import com.quasar.hpatient.model.litePalmodel.HospitalInfodb;
import com.quasar.hpatient.model.litePalmodel.KidneySourceTypedb;
import com.quasar.hpatient.model.medicalmodel.GeographyBean;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.operationmodel.AccountInfo;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.OnEditUserListener;
import com.quasar.hpatient.presenter.PostEditUserPresenter;
import com.quasar.hpatient.utils.DialogHelp;
import com.quasar.hpatient.utils.FileUtil;
import com.quasar.hpatient.utils.GetJsonDataUtil;
import com.quasar.hpatient.utils.ImageUtils;
import com.quasar.hpatient.utils.LogAndToastUtil;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.utils.UrlUtils;
import com.quasar.hpatient.utils.runtimepermissions.PermissionsManager;
import com.quasar.hpatient.utils.runtimepermissions.PermissionsResultAction;
import com.quasar.hpatient.view.personal.setup.WithDonorActivity_;
import com.quasar.hpatient.widget.EditWidget;
import com.quasar.hpatient.widget.SelectWidget;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static com.quasar.hpatient.choicePhoto.PhotoSelectorActivity.query;

/**
 * author : 许建宏
 * Date: 2017/9/30 0029
 * View:个人信息
 */
@EActivity(R.layout.activity_edituser)
public class EditUserActivity extends BaseActivity implements OnEditUserListener {

    //上传图片
    PictureConstant pictureConstant;
    PatientInfoData patient;
    Map<String, String> map = MainAppliaction.getInstance().MsgList();
    private final static String FILE_SAVEPATH = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/OSChina/Portrait/";
    private final static int CROP = 200;
    private PostEditUserPresenter postEditUserPresenter;
    HashSet<String> joblist = new HashSet<String>();
    List<KidneySourceTypedb> lidney = MainAppliaction.getInstance().getKidneySourceTypeList();
    //读取血型信息
    final List<BloodTypeInfodb> bloodTypeInfoList = MainAppliaction.getInstance().getBloodTypeInfoList();
    //记录器官来源id
    int sourceId = 0;
    //记录血型信息
    int bloodtype = 0;
    //记录手术医院id
    int HospitalId = 0;
    //记录头像
    String CorePath = null;
    //获取地理信息
    List<Aerainfodb> Geography = new ArrayList<>();
    private List<List<HospitalInfodb>> screenHospitalList = new ArrayList<>();
    /**
     * 医院筛选
     */
    List<HospitalInfodb> hospitalInfoDBList = MainAppliaction.getInstance().getHospitalInfodbList();


    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    //个人姓名
    @ViewById(R.id.ew_name)
    EditWidget ew_name;
    //昵称
    @ViewById(R.id.ew_nickname)
    EditWidget ew_nickname;
    //出生日期
    @ViewById(R.id.sw_birthday)
    SelectWidget sw_birthday;
    //血型
    @ViewById(R.id.sw_blood)
    SelectWidget sw_blood;
    //肾来源
    @ViewById(R.id.sw_source)
    SelectWidget sw_source;
    //同供体患者
    @ViewById(R.id.sw_donor)
    TextView sw_donor;
    //手术时间
    @ViewById(R.id.sw_operationday)
    SelectWidget sw_operationday;
    //手术医院
    @ViewById(R.id.ew_operation_hospital)
    TextView ew_operation_hospital;
    //联系地址
    @ViewById(R.id.ew_address)
    SelectWidget ew_address;
    //身份证
    @ViewById(R.id.ew_usid)
    EditText ew_usid;
    //性别
    @ViewById(R.id.btn1)
    RadioButton btn1;
    @ViewById(R.id.btn2)
    RadioButton btn2;
    //年龄
    @ViewById(R.id.ew_age)
    TextView ew_age;
    @ViewById(R.id.ew_phone)
    TextView ew_phone;
    //头像
    @ViewById(R.id.rv_head)
    RoundedImageView rv_head;
    @ViewById(R.id.ew_executive_doctor)
    EditWidget ew_executive_doctor;

    //主治医生
    String supervisorDoctor = "";
    String protopathy = "";

    @AfterViews
    void init() {
        ViseLog.d("enter");
        initView();
        initData();
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initView() {
        initToolbar();
        //获取个人信息
        patient = AccountInfo.loadAccount(this);

        //真实姓名
        if (patient.getRealName() != null && patient.getRealName().length() > 0) {
            if (patient.getPhone() != null && patient.getPhone().length() > 0) {
                if (patient.getPhone().equals(patient.getRealName())) {
                    ew_name.setText("");
                } else {
                    ew_name.setText(patient.getRealName());
                }
            } else {
                ew_name.setText(patient.getRealName());
            }

        }
        //昵称
        if (patient.getNick() != null && patient.getNick() != null) {

            if (patient.getPhone() != null && patient.getPhone().length() > 0) {
                if (patient.getNick().equals(patient.getPhone())) {
                    ew_nickname.setText("");
                }else{
                    ew_nickname.setText(patient.getNick());
                }
            } else {
                ew_nickname.setText(patient.getNick());
            }
        }

        //性别
        if (patient.getSex() == 1) {
            btn1.setChecked(true);
        } else {
            btn2.setChecked(true);
        }

        //出生日期
        if (patient.getBirthday() != null && patient.getBirthday().length() != 0) {
            sw_birthday.setText(patient.getBirthday().substring(0, 10));
            //根据出生日期判断年龄
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sdf.parse(patient.getBirthday());
                int age = TimeZoneUtil.getAge(date);
                ew_age.setText(age + "");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //身份证号码
        if (patient.getIdCard() != null) {
            ew_usid.setText(patient.getIdCard());
        }

        //联系地址

        if (patient.getAddress() != null) {
            ew_address.setText(patient.getAddress());
        }

        //联系电话
        if (patient.getPhone() != null) {
            ew_phone.setText(patient.getPhone());
        }
        //主管医生
        if (patient.getSupervisorDoctor() != null) {
            ew_executive_doctor.setText(patient.getSupervisorDoctor());
            supervisorDoctor = patient.getSupervisorDoctor();
        }
        //原发病
        if (patient.getProtopathy() != null) {
            protopathy = patient.getProtopathy();
        }

        //手术日期
        if (patient.getPatientOperationInfo() != null) {
            if (patient.getPatientOperationInfo().getOperationTime().length() != 0) {
                sw_operationday.setText(patient.getPatientOperationInfo().getOperationTime().substring(0, 10));
            }
        }
        //头像
        if (patient.getCover() != null && patient.getCover().length() > 0) {
            Glide.with(this).load(RetrofitConnection.PHOTOURL + patient.getCover()).into(rv_head);
            CorePath = patient.getCover();
        }

        if (patient.getPatientOperationInfo() != null) {
            //器官来源
            if (patient.getPatientOperationInfo().getSourceId() != 0) {
                for (int i = 0; i < lidney.size(); i++) {
                    if (patient.getPatientOperationInfo().getSourceId() == lidney.get(i).getPrimaryid()) {
                        sw_source.setText(lidney.get(i).getName());
                        sourceId = patient.getPatientOperationInfo().getSourceId();
                        break;
                    }
                }
            }
            //手术医院
            if (patient.getPatientOperationInfo().getHospitalId() != 0) {

                for (int i = 0; i < hospitalInfoDBList.size(); i++) {
                    if (patient.getPatientOperationInfo().getHospitalId() == hospitalInfoDBList.get(i).getPrimaryid()) {
                        ew_operation_hospital.setText(hospitalInfoDBList.get(i).getName());
                        HospitalId = patient.getPatientOperationInfo().getHospitalId();
                        break;
                    }
                }
            }
        }

        //血型
        if (patient.getBloodId() != 0) {
            for (int i = 0; i < bloodTypeInfoList.size(); i++) {
                if (patient.getBloodId() == bloodTypeInfoList.get(i).getPrimaryid()) {
                    sw_blood.setText(bloodTypeInfoList.get(i).getName());
                    bloodtype = patient.getBloodId();
                    Xuexingname = bloodTypeInfoList.get(i).getName();
                    break;
                }
            }
        }


        ew_name.setLetfTextFwatch(new TextWatcher() {
            String str;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String strs = ew_name.getText().toString();
                str = StringUtils.stringFilter(strs.toString());
                if (!strs.equals(str)) {
                    ew_name.setText(str);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //主管医生
        //ew_executive_doctor
    }

    //点击电话号码跳转到拨号界面
    @Click(R.id.ew_phone)
    public void ew_phone() {
        String phone = ew_phone.getText().toString();
        if (phone.length() != 0) {
            Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone));
            startActivity(intent);
        }

    }


    //提交个人资料
    @Click(R.id.submit)
    public void submit() {

        //姓名
        String name = ew_name.getText().toString().trim();
        if (name.length() == 0) {
            msg("个人姓名不能为空");
            return;
        }
        //昵称
        String nickname = ew_nickname.getText().toString().trim();
        if (nickname.length() == 0) {
            nickname = "";
        }
        //性别
        int sex;
        if (btn1.isChecked()) {
            sex = 1;
        } else {
            sex = 0;
        }
        //出生日期
        String birthday = sw_birthday.getText().toString().trim();
        if (birthday.length() == 0) {
            birthday = "";
        } else {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(birthday);
            stringBuffer.append(" 00:00:00");
            birthday = stringBuffer.toString();
        }
        //手术日期
        String operationday = sw_operationday.getText().toString().trim();
        if (operationday.length() == 0) {
            operationday = "";
        } else {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(operationday);
            stringBuffer.append(" 00:00:00");
            operationday = stringBuffer.toString();
        }
        //地址
        String address = ew_address.getText().toString().trim();
        if (address.length() == 0) {
            address = "";
        }

        //主治医生
        String doctorx = ew_executive_doctor.getText().toString();
        if (doctorx != null) {
            supervisorDoctor = doctorx;
        }


        //身份证号码
        String usid = ew_usid.getText().toString().trim();
        if (usid.length() == 0) {
            usid = "";
        } else {
            //验证身份证号码格式
            if (!UrlUtils.validateIDCardNumber(usid)) {
                msg("身份证格式不正确");
                ew_usid.requestFocus();
                return;
            }
        }

        //主管医生信息supervisorDoctor

        final String finalNickname = nickname;
        final String finalName = name;
        final String finalUsid = usid;
        final String finalBirthday = birthday;
        final int finalSex = sex;
        final String finalOperationday = operationday;
        final String finalAddress = address;
        pictureConstant = new PictureConstant(new PictureConstant.updateUiInit() {
            @Override
            public void updateInit(String path) {
                postEditUserPresenter.PostEditUserOperation(path, finalNickname,
                        finalName, bloodtype + "",
                        finalUsid, finalBirthday,
                        finalSex + "", finalOperationday,
                        HospitalId + "", sourceId + "",
                        ConstantManger.userType, finalAddress, supervisorDoctor, protopathy);
            }

            @Override
            public void onErrPhoto(String errVal) {
                dessDialog();
            }
        });

        if (photoModel != null && new File(photoModel.getOriginalPath()).length() != 0) {
            List<File> fileList = new ArrayList<>();
            fileList.add(new File(photoModel.getOriginalPath()));
            pictureConstant.PostPicture(fileList);
            showDialog();
        } else {
            postEditUserPresenter.PostEditUserOperation(CorePath, finalNickname,
                    finalName, bloodtype + "",
                    finalUsid, finalBirthday,
                    finalSex + "", finalOperationday,
                    HospitalId + "", sourceId + "",
                    ConstantManger.userType, finalAddress, supervisorDoctor, protopathy);
        }
    }

    //提交个人信息更新发送通知更新个人信息
    public void EventUserInfo() {
        UpdateEvent updateEvent = new UpdateEvent();
        updateEvent.type = ConstantManger.eventUserInfo;
        EventBus.getDefault().post(updateEvent);
    }

    @Override
    protected void initData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        postEditUserPresenter = new PostEditUserPresenter(this);
    }

    //患者头像
    @Click(R.id.rv_head)
    public void rv_head() {
        requestPermissions();
        DialogHelp.getSelectDialog(this, "选择图片", getResources().getStringArray(R.array.choose_picture), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                goToSelectPicture(i);
            }
        }).show();
    }

    //选择时间
    @Click(R.id.sw_birthday)
    public void sw_birthday() {
        //选择手术日期
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, i);
                calendar.set(Calendar.MONTH, i2);
                calendar.set(Calendar.DAY_OF_MONTH, i3);

                sw_birthday.setText("" + TimeZoneUtil.sdf.format(calendar.getTime()).substring(0, 10));
                Date date = calendar.getTime();
                int age = TimeZoneUtil.getAge(date);
                ew_age.setText(age + "");
            }
        }, year, month, day);
        DatePicker datePicker = datePickerDialog.getDatePicker();
        datePicker.setMaxDate(TimeZoneUtil.getStringToDate(TimeZoneUtil.sdf.format(new Date()), "yyyy-MM-dd"));

        datePickerDialog.setTitle("选择出生日期");
        datePickerDialog.show();
    }

    public static final int ACTION_TYPE_ALBUM = 0;//相册
    public static final int ACTION_TYPE_PHOTO = 1; //照相

    private void goToSelectPicture(int position) {
        switch (position) {
            case ACTION_TYPE_ALBUM:
                startImagePick();
                break;
            case ACTION_TYPE_PHOTO:
                catchPicture();
                break;
            default:
                break;
        }
    }


    /**
     * 拍照
     */
    private Uri photoUri;
    private static final int REQUEST_CAMERA = 1;

    private void catchPicture() {
//		CommonUtils.launchActivityForResult(this, new Intent(
//				MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_CAMERA);

        Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                "yyyy_MM_dd_HH_mm_ss");
        byte[] filenames = timeStampFormat.format(new java.util.Date())
                .getBytes();
        String filename = null;
        try {
            filename = new String(filenames, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, filename);
        photoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        intent1.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent1, REQUEST_CAMERA);
    }

    PhotoModel photoModel = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CAMERA) {
            Uri ri = null;
            if (data != null) {
                ri = data.getData();
            }
            if (ri == null) {
                if (photoUri != null) {
                    ri = photoUri;
                }
            }
            ViseLog.d("获取到图片地址" + ri);
            String file = Global.getPath(this, ri);
            if (photoModel != null) {
                photoModel = new PhotoModel(file);
            } else {
                photoModel = new PhotoModel(query(this, ri));
            }

            if (photoModel == null) {
                return;
            } else {
                if (photoModel.getOriginalPath().length() > 0) {
                    File file1 = new File(photoModel.getOriginalPath());
                    if (file1.length() != 0) {
                        Glide.with(this).load(photoModel.getOriginalPath()).into(rv_head);
                        ViseLog.d("返回来的图片地址" + photoModel.getOriginalPath());
                    }
                }

            }
        } else if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP) {
            if (data != null) {
                startActionCrop(data.getData());// 选图后裁剪
            }
        } else if (requestCode == 11) {
            if (protraitPath != null) {
                ViseLog.d("裁剪后返回的图片地址" + protraitPath);
                if (protraitPath == null) {
                    msg("图片路径出错");
                    return;
                }
                File file1 = new File(protraitPath);
                if (file1.length() != 0) {
                    photoModel = new PhotoModel(protraitPath);
                    if (photoModel == null) {
                        return;
                    } else {
                        if (protraitPath != null && protraitPath.length() > 0) {
                            Glide.with(this).load(protraitPath).into(rv_head);
                        }
                    }
                }
            }
        }
    }

    //器官来源
    @Click(R.id.sw_source)
    public void sw_source() {
        //选择器官来源
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = lidney.get(options1).getPickerViewText();
                sw_source.setText(tx);
                sourceId = lidney.get(options1).getId();

//                if(lidney.get(options1).getPickerViewText().equals("亲属活体肾移植")){
//                    WithDonorActivity_.intent(EditUserActivity.this).start();
//                }
            }
        })

                .setTitleText("器官来源选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(lidney);//三级选择器
        pvOptions.show();

        //WithDonorActivity
    }

    String Xuexingname;

    //血型选择
    @Click(R.id.sw_blood)
    public void sw_blood() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(final int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                final String tx = bloodTypeInfoList.get(options1).getPickerViewText();
                if (tx.indexOf("阴性") != -1) {
                    new AlertDialog.Builder(EditUserActivity.this).setTitle("确定选择\t" + tx + "\t吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击“确认”后的操作
                                    sw_blood.setText(tx);
                                    bloodtype = bloodTypeInfoList.get(options1).getPrimaryid();
                                    Xuexingname = tx;
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击“返回”后的操作,这里不设置没有任何操作
                                    sw_blood.setText(Xuexingname);
                                }
                            }).show();
                } else {
                    sw_blood.setText(tx);
                    bloodtype = bloodTypeInfoList.get(options1).getPrimaryid();
                    Xuexingname = tx;
                    sw_blood.setText(Xuexingname);
                }
            }
        })

                .setTitleText("血型选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(bloodTypeInfoList);//三级选择器
        pvOptions.show();
    }

    //手术日期选择
    @Click(R.id.sw_operationday)
    public void sw_operationday() {
        //选择手术日期
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, i);
                calendar.set(Calendar.MONTH, i2);
                calendar.set(Calendar.DAY_OF_MONTH, i3);

                sw_operationday.setText("" + TimeZoneUtil.sdf.format(calendar.getTime()).substring(0, 10));
            }
        }, year, month, day);
        //设置最大日期
        DatePicker datePicker = datePickerDialog.getDatePicker();
        datePicker.setMaxDate(TimeZoneUtil.getStringToDate(TimeZoneUtil.sdf.format(new Date()), "yyyy-MM-dd"));
        datePickerDialog.setTitle("选择出生日期");
        datePickerDialog.show();
    }

    //判断23以上的动态申请权限
    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //权限借口回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @android.support.annotation.NonNull String[] permissions, @android.support.annotation.NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    @Override
    public void onSuccess(DataStateResult data) {
        ViseLog.d("onNext" + data);
        msg(map.get(data.getMsgCode()));
        EventUserInfo();
        dessDialog();
    }

    @Override
    public void onError(String msg) {
        ViseLog.d("onError" + msg);
        if (msg != null) {
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {
        dessDialog();
    }

    @Override
    public void onWithDonorSuccess(DataStateResult data) {

    }

    @Override
    public void onWithObtain(DataHeadResult<PatientInfoData> dataDataHeadResult) {
        if (dataDataHeadResult.getData() != null) {
            sw_donor.setText(dataDataHeadResult.getData().getRealName());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取同共体患者
//        postEditUserPresenter.SelectTheTotalBody2Data();
    }

    //医院选择
    @Click(R.id.ew_operation_hospital)
    public void ew_operation_hospital() {
        screenHospital();
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                ew_operation_hospital.setText(screenHospitalList.get(options1).get(options2).getName());
                HospitalId = screenHospitalList.get(options1).get(options2).getPrimaryid();
            }
        })

                .setTitleText("医院选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(Geography, screenHospitalList);//三级选择器  ,screenHospitalList
        pvOptions.show();
    }

    //根据省市信息获取医院
    public void screenHospital() {
        Geography.clear();
        Geography.addAll(MainAppliaction.getInstance().Geography());
        int num = Geography.size();
        int size = hospitalInfoDBList.size();
        for (int i = 0; i < num; i++) {
            ArrayList<HospitalInfodb> options1 = new ArrayList<>();
            for (int z = 0; z < size; z++) {

                if (Geography.get(i).getPrimary() == hospitalInfoDBList.get(z).getProvinceID()) {
                    options1.add(hospitalInfoDBList.get(z));
                }
            }
            screenHospitalList.add(options1);
        }
    }

    //选择地址
    @Click(R.id.ew_address)
    public void ew_address() {

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);

                ew_address.setText(tx);
            }
        })
                .setTitleText("地区选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    /**
     * 添加地址选择
     */
    private Thread thread;
    private boolean isLoaded = false;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private ArrayList<GeographyBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    LogAndToastUtil.toast(EditUserActivity.this, "解析数据失败", "");
                    break;

            }
        }
    };


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<GeographyBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public ArrayList<GeographyBean> parseData(String result) {//Gson 解析

        ArrayList<GeographyBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                GeographyBean entity = gson.fromJson(data.optJSONObject(i).toString(), GeographyBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    private String protraitPath;
    private File protraitFile;
    private Uri cropUri;

    /**
     * 选择图片裁剪
     */
    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        }
    }

    /**
     * 拍照后裁剪
     *
     * @param data 原始图片
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent,
                11);
    }

    // 裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            msg("无法保存上传的头像，请检查SD卡是否挂载");
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath)) {
            thePath = ImageUtils.getAbsoluteImagePath(this, uri);
        }
        String ext = FileUtil.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "osc_crop_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        cropUri = Uri.fromFile(protraitFile);
        return this.cropUri;
    }
}
